<!--
 * @Description: 添加/展示/编辑消息模板的弹窗
 * @Version: 1.0
 * @Autor: chen_yt
 * @Date: 2020-11-02 17:15:31
 * @LastEditors: chen_yt
 * @LastEditTime: 2022-02-21 10:50:41
-->

<template>
  <div class="dialog-for-column">
    <fks-dialog
      v-if="Visible"
      :class="operateType == 'show' ? 'view' : ''"
      :visible.sync="Visible"
      :append-to-body="true"
      width="960px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="close"
    >
      <template slot="title">
        <i :class="iconClass" />
        <span>{{ DialogTitle }}</span>
      </template>

      <div class="column-edit">
        <fks-form
          ref="Form"
          v-loading="loading"
          :model="Form"
          labfks-position="left"
          labfks-width="84px"
          :disabled="operateType == 'show'"
          :rules="rules"
        >
          <fks-form-item
            :span="12"
            :label="LANG.TEMPLATE_NAME"
            prop="templateName"
          >
            <fks-input
              v-model="Form.templateName"
              maxlength="50"
              show-word-limit
            />
          </fks-form-item>
          <fks-form-item
            :span="12"
            :label="LANG.MSG_SEND_TYPE"
            prop="supportedMsgSendTypes"
          >
            <fks-select
              v-model="Form.supportedMsgSendTypes"
              style="width: 100%"
              disabled
              @change="msgSendTypeChange()"
            >
              <fks-option
                v-for="item in msgSendTypeList"
                :key="item.code"
                :value="item.code"
                :label="item[$lang]"
              />
            </fks-select>
          </fks-form-item>

          <fks-form-item
            :span="24"
            :label="LANG.SEND_PARAMS"
            prop="meta"
          >
            <fks-table
              :data="Form.defaultParams"
              style="width: 100%"
              size="samll"
            >
              <fks-table-column
                label="#"
                type="index"
                align="center"
                :resizable="false"
              />
              <fks-table-column
                prop="name"
                :label="LANG.PARAM_NAME"
                align="center"
              >
                <template slot-scope="scope">
                  <div>{{ scope.row.name }}</div>
                </template>
              </fks-table-column>
              <fks-table-column
                prop="value"
                :label="LANG.PARAM_DEFAULT_VALUE"
                align="center"
              >
                <div slot-scope="scope">
                  <div v-if="!scope.row.type">
                    {{ scope.row.value }}
                  </div>
                  <div v-if="scope.row.type == 'edit'">
                    <fks-input
                      v-model="scope.row.value"
                      maxlength="50"
                      @keyup.enter.native="rowSave(scope.row)"
                    />
                  </div>
                </div>
              </fks-table-column>

              <fks-table-column
                :label="LANG.OPERATION"
                width="120"
                align="center"
              >
                <span slot-scope="scope">
                  <fks-button
                    v-if="!scope.row.type"
                    class="table-column-opt-button"
                    type="text"
                    @click="editHandler(scope.row)"
                  >{{ LANG.EDIT }}</fks-button>
                  <fks-button
                    v-if="scope.row.type == 'edit'"
                    class="table-column-opt-button"
                    type="text"
                    @click="rowSave(scope.row)"
                  >{{ LANG.SAVE }}</fks-button>
                  <!-- <fks-button
                        class="table-column-opt-button"
                        @click="cancelAdd(scope)"
                        type="text"
                        style="color: #ff4d4f"
                        >{{ LANG.DELETE }}</fks-button
                  >-->
                </span>
              </fks-table-column>
            </fks-table>
          </fks-form-item>

          <!-- 模板可变字段的参数 -->

          <fks-form-item
            :span="24"
            :label="LANG.TEMPLATE_PARAMS"
            prop="meta"
          >
            <div
              v-show="operateType != 'show'"
              style="padding-bottom: 16px; text-align: right"
            >
              <fks-button
                icon="fks-icon-plus"
                size="small"
                @click="addTemplateParam"
              >
                {{ LANG.ADD }}
              </fks-button>
            </div>
            <fks-table
              :data="Form.paramsList"
              style="width: 100%"
              size="samll"
            >
              <fks-table-column
                label="#"
                type="index"
                align="center"
                :resizable="false"
              />
              <fks-table-column
                prop="name"
                :label="LANG.PARAM_NAME"
                align="center"
              >
                <div slot-scope="scope">
                  <div v-if="!scope.row.type">
                    {{ scope.row.name }}
                  </div>
                  <div v-if="scope.row.type == 'edit'">
                    <fks-input
                      v-model="scope.row.name"
                      maxlength="50"
                      @keyup.enter.native="rowSave(scope.row)"
                    />
                  </div>
                </div>
              </fks-table-column>
              <fks-table-column
                prop="value"
                :label="LANG.PARAM_DEFAULT_VALUE"
                align="center"
              >
                <div slot-scope="scope">
                  <div v-if="!scope.row.type">
                    {{ scope.row.value }}
                  </div>
                  <div v-if="scope.row.type == 'edit'">
                    <fks-input
                      v-model="scope.row.value"
                      maxlength="50"
                      @keyup.enter.native="rowSave(scope.row)"
                    />
                  </div>
                </div>
              </fks-table-column>

              <fks-table-column
                :label="LANG.OPERATION"
                align="center"
                width="120"
              >
                <div slot-scope="scope">
                  <fks-button
                    v-if="!scope.row.type"
                    class="table-column-opt-button"
                    type="text"
                    @click="editHandler(scope.row)"
                  >
                    {{ LANG.EDIT }}
                  </fks-button>
                  <fks-button
                    v-if="scope.row.type == 'edit'"
                    class="table-column-opt-button"
                    type="text"
                    @click="rowSave(scope.row)"
                  >
                    {{ LANG.SAVE }}
                  </fks-button>
                  <fks-button
                    class="table-column-opt-button"
                    type="text"
                    style="color: #ff4d4f"
                    @click="cancelAdd(scope, Form.paramsList)"
                  >
                    {{ LANG.DELETE }}
                  </fks-button>
                </div>
              </fks-table-column>
            </fks-table>
          </fks-form-item>

          <fks-form-item
            v-show="!loading"
            :span="24"
            :label="LANG.PARAMS_CONTENT"
            style="margin-bottom: 1px"
          >
            <Editor
              v-if="operateType != 'show'"
              ref="Editor"
              :height="300"
              :value.sync="Form.template"
              :custom-setting="EditorSetting"
            />
            <fks-input
              v-model="Form.template"
              :style="operateType != 'show' ? 'margin-top: 16px' : ''"
              type="textarea"
              :rows="10"
              :placeholder="LANG.DEMO_TEMPLATE"
            />
          </fks-form-item>
        </fks-form>
      </div>
      <!-- 提交按钮 -->
      <template slot="footer">
        <fks-button
          v-show="operateType != 'show' && !loading"
          type="primary"
          icon="fks-icon-check"
          @click="submit"
        >
          {{ LANG.SAVE }}
        </fks-button>
      </template>
    </fks-dialog>
  </div>
</template>

<script>
import Editor from '@/components/TinyMceEdit'
import { addTemplate, getDefaultParams } from '../../api'
import { ENUM } from '@/store/State/stateTypes'
import { getMsgTemplateById } from '../..//api'

export default {
  name: 'MsgAndEmail',
  components: {
    Editor
  },
  props: {
    visible: {
      type: Boolean
    },
    operateType: {
      type: String,
      default: 'new'
    },
    templateId: {
      type: String
    },
    msgSendType: {
      type: String
    }
  },
  data() {
    return {
      Visible: false,
      loading: true,
      Form: {},
      defaultParams: [],
      paramsList: [],
      rules: {
        templateName: [{ required: true }]
      }
    }
  },
  computed: {
    DialogTitle() {
      if (this.operateType == 'new') return this.LANG.ADD
      if (this.operateType == 'edit') return this.LANG.EDIT
      return this.LANG.VIEW
    },
    msgSendTypeList() {
      return this.$store.state[ENUM].msgSendType || []
    },
    msgType() {
      return this.$store.state[ENUM].msgType || []
    },
    iconClass() {
      if (this.operateType == 'new') return 'fks-icon-plus'
      if (this.operateType == 'edit') return 'fks-icon-edit'
      return 'fks-icon-view'
    },
    EditorSetting() {
      return {
        toolbar:
          'undo redo | fullscreen | formatselect alignleft aligncenter alignright alignjustify | link unlink | numlist bullist |  image table emoticons | bold italic underline strikethrough | indent outdent | codesample | fontselect fontsizeselect forecolor backcolor | superscript subscript| formatpainter  removeformat '
      }
    }
  },

  watch: {
    visible(val) {
      this.Visible = val
      if (val) {
        this.resetData()
        this.initData()
      }
    }
  },
  mounted() {},
  methods: {
    addTemplateParam() {
      this.Form.paramsList.push({
        name: '',
        value: '',
        type: 'edit'
      })
    },

    rowSave(data) {
      //判断是否存在同名
      if (data.name == '') {
        this.$message({
          type: 'error',
          message: this.LANG.ERROR_PARAM_NAME_NULL
        })
        return
      }
      let allParams = [...this.Form.defaultParams, ...this.Form.paramsList]
      let same = 0
      for (let i = 0; i < allParams.length; i++) {
        if (allParams[i].name == data.name) {
          same++
          if (same > 1) {
            this.$message({
              type: 'error',
              message: this.LANG.ERROR_PARAM_NAME_DUPLICATE
            })
            return
          }
        }
      }
      data.type = ''
    },
    editHandler(data) {
      data.type = 'edit'
    },
    cancelAdd(data, list) {
      list.splice(data.$index, 1)
    },

    msgSendTypeChange() {
      let index = this.Form.supportedMsgSendTypes
      this.getDefaultParams(index)
    },

    getDefaultParams(index) {
      return getDefaultParams(index)
        .then((res) => {
          if (res.status) {
            this.defaultParams = res.data ? res.data.split(',') : []
          }
        })
        .catch(() => {})
    },

    /**
     * @description: 将form处理为与接口对应的形式
     * @param {Object} form 表单的form
     * @return {Object} newForm 用于提交的form
     */
    dealForSubmit(form) {
      let newForm = form
      newForm.supportedMsgTypes = newForm.msgType.join()
      let allParams = [...form.defaultParams, ...form.paramsList]
      let arr = []
      let obj = {}
      allParams.forEach((item) => {
        arr.push(item.name)
        obj[item.name] = item.value
      })
      newForm.templateParamList = arr.join()
      newForm.templateParamDefaultValue = JSON.stringify(obj)

      return newForm
    },

    submit() {
      this.$refs['Form'].validate((valid) => {
        if (valid) {
          this.submitCheck()
        }
        if (!valid) {
          this.$message({
            type: 'error',
            message: this.LANG.ERROR_UNDO
          })
          return
        }
      })
    },

    submitCheck() {
      let allParams = [...this.Form.defaultParams, ...this.Form.paramsList]
      for (let i = 0; i < allParams.length; i++) {
        if (allParams[i].type == 'edit') {
          this.$message({
            type: 'error',
            message: this.LANG.ERROR_PARAM_NOT_SAVE
          })
          return
        }
      }
      this.submitForm()
    },

    submitForm: async function () {
      let submitForm = this.dealForSubmit(this.Form)
      addTemplate(submitForm, this.operateType)
        .then((res) => {
          if (res.status) {
            this.$message({
              type: 'success',
              message:
                this.operateType == 'new'
                  ? this.LANG.ADD_SUCCESS
                  : this.LANG.EDIT_SUCCESS
            })
            this.$emit('submit')
          }
        })
        .catch(() => {})
    },

    resetData() {
      this.Form = {
        msgType: [],
        paramsList: [],
        defaultParams: [],
        supportedMsgSendTypes: this.msgSendType,
        template: this.LANG.DEMO_TEMPLATE
      }
      this.defaultParams = []
      this.paramsList = []
    },
    cancel() {
      this.close()
    },
    close() {
      this.$emit('close')
      this.resetData()
    },

    pushIntoTable(name, valueObject, table) {
      let temp = {
        name: name,
        value: valueObject[name],
        type: ''
      }
      table.push(temp)
    },

    /**
     * @description: 初始化Dialog
     *
     */
    initData: async function () {
      this.loading = true

      await this.getDefaultParams(this.msgSendType)

      if (this.operateType == 'new') {
        for (let i = 0; i < this.defaultParams.length; i++) {
          this.pushIntoTable(this.defaultParams[i], [], this.Form.defaultParams)
        }
        this.loading = false
      }

      if (this.operateType == 'edit' || this.operateType == 'show') {
        getMsgTemplateById(this.templateId)
          .then((res) => {
            if (res.status) {
              let templateInfo = res.data

              //勾选的消息类型
              if (templateInfo.supportedMsgTypes) {
                this.Form.msgType = templateInfo.supportedMsgTypes.split(',')
              }

              //模板参数/发送参数置入
              if (templateInfo.templateParamList) {
                //此处去重
                //消息发送方式带来的必选字段
                //不会出现在消息参数中

                let arr = templateInfo.templateParamList.split(',')

                for (let i = 0; i < arr.length; i++) {
                  let item = arr[i]
                  if (this.defaultParams.indexOf(item) < 0)
                    //模板参数
                    this.paramsList.push(item)
                }
              }

              let paramsValueList = JSON.parse(
                templateInfo.templateParamDefaultValue
              )

              for (let i = 0; i < this.paramsList.length; i++) {
                this.pushIntoTable(
                  this.paramsList[i],
                  paramsValueList,
                  this.Form.paramsList
                )
              }

              for (let i = 0; i < this.defaultParams.length; i++) {
                this.pushIntoTable(
                  this.defaultParams[i],
                  paramsValueList,
                  this.Form.defaultParams
                )
              }
              this.Form = { ...this.Form, ...templateInfo }
            }
            this.loading = false
          })
          .catch(() => {
            this.loading = false
          })
      }
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .fks-dialog__body {
  padding-bottom: 0;
}
</style>
